package com.google.code.p.restrpc.mon.web.registry;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.google.code.p.restrpc.directory.Registry;
import com.google.code.p.restrpc.directory.RemoteServiceDefinition;
import com.google.code.p.restrpc.directory.RemoteServiceDefinitionPack;
import com.google.code.p.restrpc.directory.spring.DirectoryServiceFactoryBean;

public class RegistryMonitor {

    public static final Map EMPTY_MAP = new HashMap(0);
    
    public Map registrySettings(Map parameters) {
        DirectoryServiceFactoryBean factoryBean = DirectoryServiceFactoryBean.getInstance();
        if (factoryBean == null) { 
            return EMPTY_MAP;
        }
        
        Map result = new HashMap();
        result.put("heartbeat",factoryBean.getHeartbeat());
        return result;
    }
    
    public String[] serviceNames(Map parameters) {
        Registry registry = DirectoryServiceFactoryBean.getRegistry();;
        if (registry == null) {
            return ArrayUtils.EMPTY_STRING_ARRAY;
        }
        
        return registry.getServiceNames();
    }
    
    public RemoteServiceDefinitionPack serviceDefinitions(Map parameters) {
        Registry registry = DirectoryServiceFactoryBean.getRegistry();;
        if (registry == null) {
            return null;
        }
        
        String[] serviceNames = (String[]) parameters.get("serviceName");
        if (serviceNames == null || serviceNames.length == 0) {
            return null;
        }
        String serviceName = serviceNames[0];
        if (StringUtils.isEmpty(serviceName)) {
            return null;
        }
        
        return registry.lookup(serviceName, -1l);
    }
    
}
